package project.newCode.bbhierarchy;

import project.newCode.Hitrecord;
import project.newCode.Ray;
import project.newCode.surfaces.Box;
import project.newCode.surfaces.Hittable;

public class BBNode implements Hittable{

	protected Hittable right;
	protected Hittable left;
	protected Box bbox;

	public BBNode() {
		super();
	}

	@Override
	public boolean hit(Ray hittingray, double t0, double t1, Hitrecord rec) {
		if(bbox.hit(hittingray, t0, t1, rec)){
			Hitrecord lrec = new Hitrecord(rec.hitCounter+1);
			Hitrecord rrec = new Hitrecord(rec.hitCounter+1);
			boolean lhit = ((left!=null) && left.hit(hittingray, t0, t1, lrec));
			boolean rhit = ((right!=null) && right.hit(hittingray, t0, (float) Math.min(t1,lrec.t), rrec));
			//boolean rhit = ((right!=null) && right.hit(hittingray, t0, t1, rrec));
			if(lhit && rhit) {
				if(lrec.t < rrec.t) {
					lrec.copyInto(rec);
				}
				else {
					rrec.copyInto(rec);
				}
				rec.hitCounter = lrec.hitCounter+rrec.hitCounter;
				return true;
			}
			if(lhit) {
				lrec.copyInto(rec);
				rec.hitCounter = lrec.hitCounter+rrec.hitCounter;
				return true;
			}
			if(rhit) {
				rrec.copyInto(rec);
				rec.hitCounter = lrec.hitCounter+rrec.hitCounter;
				return true;
			}
			rec.hitCounter = lrec.hitCounter+rrec.hitCounter;
			return false;
		}
		else {
			return false;
		}
	}

	@Override
	public Box boundingbox() {
		// TODO Auto-generated method stub
		return bbox;
	}

	public void combinebox(Box right, Box left) {
		this.bbox = Box.combine(right,left);
	}

}